import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { userApi } from '../services/user';

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref(null);

  // 计算属性
  const isLoggedIn = computed(() => !!currentUser.value);
  const userRole = computed(() => currentUser.value?.userRole || 'user');

  // 方法
  async function login(credentials) {
    try {
      const userData = await userApi.login(credentials);
      currentUser.value = userData;
      localStorage.setItem('user', JSON.stringify(userData));
      return userData;
    } catch (error) {
      throw error;
    }
  }

  async function register(userData) {
    try {
      const result = await userApi.register(userData);
      return result;
    } catch (error) {
      throw error;
    }
  }

  async function logout() {
    try {
      await userApi.logout();
    } catch (error) {
      console.error('登出API调用失败:', error);
    } finally {
      // 无论API是否成功，都清理本地状态
      currentUser.value = null;
      localStorage.removeItem('user');
    }
  }

  async function resetPassword(passwordData) {
    try {
      const result = await userApi.resetPassword(passwordData);
      return result;
    } catch (error) {
      throw error;
    }
  }

  async function fetchCurrentUser() {
    try {
      const userData = await userApi.getCurrentUser();
      currentUser.value = userData;
      return userData;
    } catch (error) {
      // 如果获取用户信息失败，清理本地状态
      logout();
      throw error;
    }
  }

  async function updateUser(payload) {
    // payload: { id, userName?, userAvatar? }
    const ok = await userApi.update(payload);
    if (ok) {
      // 本地同步更新
      currentUser.value = { ...currentUser.value, ...payload };
      localStorage.setItem('user', JSON.stringify(currentUser.value));
    }
    return ok;
  }
  
  function initFromStorage() {
    const storedUser = localStorage.getItem('user');
    
    if (storedUser) {
      try {
        const userData = JSON.parse(storedUser);
        currentUser.value = userData;
      } catch (error) {
        console.error('解析存储的用户信息失败:', error);
        logout();
      }
    }
  }

  // 新增：延迟验证token有效性的方法
  async function validateTokenSilently() {
    if (!currentUser.value) return false;
    
    try {
      await userApi.getCurrentUser();
      return true;
    } catch (error) {
      console.warn('Token验证失败，需要重新登录');
      logout();
      return false;
    }
  }

  return {
    // 状态
    currentUser,
    
    // 计算属性
    isLoggedIn,
    userRole,
    
    // 方法
    login,
    register,
    logout,
    resetPassword,
    fetchCurrentUser,
    updateUser,
    initFromStorage,
    validateTokenSilently
  };
});
